package com.sphd.restaurantsystem.activitys.funding;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.sphd.restaurantsystem.R;
import com.sphd.restaurantsystem.adapters.MoneyRecordAdapter;
import com.sphd.restaurantsystem.base.BaseActivity;
import com.sphd.restaurantsystem.base.RestaurantUrl;
import com.sphd.restaurantsystem.info.InvestRuleInfo;
import com.sphd.restaurantsystem.info.InvestorInfo;
import com.sphd.restaurantsystem.info.LoginInfo;
import com.sphd.restaurantsystem.info.MoneyRecordInfo;
import com.sphd.restaurantsystem.info.RestaurantInfo;
import com.sphd.restaurantsystem.presenter.MoneyRecordPresenterImpl;
import com.sphd.restaurantsystem.utils.Constant;
import com.sphd.restaurantsystem.view.MoneyRecordView;
import com.wzh.frame.utils.BigDisMailUtils;
import com.wzh.frame.utils.StringUtils;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 资金记录
 */
public class  MoneyRecordActivity extends BaseActivity implements MoneyRecordView, SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    Intent intent;
    Bundle bundle;
    RestaurantInfo restaurantInfo;
    MoneyRecordPresenterImpl moneyRecordPresenter;
    InvestorInfo investorInfo;
    MoneyRecordAdapter moneyRecordAdapter;
    @BindView(R.id.menu_close_account)
    TextView menuCloseAccount;
    @BindView(R.id.btn_over)
    Button btnOver;
    LoginInfo loginInfo;
    double sum_account = 0;
    InvestRuleInfo investRuleInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_money_record);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        mySwf.setOnRefreshListener(this);
    }

    private void initView() {
        setTitleBar(toolbar, "资金记录");
        loginInfo = DataSupport.findLast(LoginInfo.class);
        intent = getIntent();
        bundle = intent.getExtras();
        investRuleInfo = (InvestRuleInfo) bundle.getSerializable(Constant.INVESTRULE);
        investorInfo = (InvestorInfo) bundle.getSerializable(Constant.INVESTOR);

        if (investorInfo.getAccount_status() == 1) {
            menuCloseAccount.setText("关闭账户");
        } else {
            menuCloseAccount.setText("开启账户");
        }

        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        moneyRecordPresenter = new MoneyRecordPresenterImpl(this);
        loginInfo = DataSupport.findLast(LoginInfo.class);
        // TODO: 2016/12/30
        if (loginInfo.getStaff_auth() == 6) {
            menuCloseAccount.setVisibility(View.GONE);
            btnOver.setVisibility(View.GONE);
        }
        initAdapter();
        addData();
    }

    private void addData() {
        moneyRecordPresenter.addData(RestaurantUrl.Httptitle + RestaurantUrl.ACCOUNTRECORD + "cgid=" + restaurantInfo.getId() +
                "&staffid=" + investorInfo.getAccount_staffid());
    }

    private void initAdapter() {
        setRefresh(mySwf);
        setRecy(myRecy);
        moneyRecordAdapter = new MoneyRecordAdapter(R.layout.item_money_accout_details, new ArrayList<>());
        myRecy.setAdapter(moneyRecordAdapter);
    }

    @Override
    public void getList(List<MoneyRecordInfo> moneyRecordInfoList) {
        moneyRecordAdapter.setNewData(moneyRecordInfoList);
        mySwf.setRefreshing(false);
    }

    @Override
    public void sumAccount(double sum_account) {
        this.sum_account = sum_account;
    }

    @OnClick({R.id.menu_close_account, R.id.btn_over})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.menu_close_account:
                if (investorInfo.getAccount_status() == 1) {
                    sendDialog("是否将账户关闭", "●账户不再产生分红", 0);
                } else {
                    sendDialog("是否将账户开启", "●该账户继续产生分红", 1);
                }
                break;
            case R.id.btn_over:
                addMoney();
                break;
        }
    }

    private void sendDialog(String s1, String s2, final int i) {


        AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle(s1).setMessage(s2).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        closeAccount(dialog, i);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        }).create();
        alertDialog.setCanceledOnTouchOutside(false);//使除了dialog以外的地方不能被点击
        alertDialog.show();

    }

    private void closeAccount(DialogInterface dialog, int i) {
        moneyRecordPresenter.setOpenCloseDialog(RestaurantUrl.Httptitle + RestaurantUrl.CLOSEACCOUNT + "id=" +
                investorInfo.getId() + "&status=" + i, dialog);
    }

    private void addMoney() {
        View view = View.inflate(this, R.layout.dialog_add, null);
        TextView mAccountMoney = (TextView) view.findViewById(R.id.m_account_money);
        final EditText mAddMoney = (EditText) view.findViewById(R.id.m_add_money);
        Button mSave = (Button) view.findViewById(R.id.m_save);
        Button mCancle = (Button) view.findViewById(R.id.m_cancle);
        mAccountMoney.setText(BigDisMailUtils.turnTrim(sum_account, Constant.DECIMAL_POINT_TWO));

        final AlertDialog alertDialog = new AlertDialog.Builder(this).setView(view).create();
        alertDialog.setCanceledOnTouchOutside(false);//使除了dialog以外的地方不能被点击
        alertDialog.show();
        mSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addMoneyDialog(mAddMoney.getText().toString(), alertDialog);
            }
        });
        mCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

    private void addMoneyDialog(String msg, AlertDialog alertDialog) {
        if (StringUtils.isEmpty(msg)) {
            toast("请输入追加的金额");
        } else {
            if (Double.parseDouble(msg) <= 0) {
                toast("请输入合理的金额");
            } else {
                moneyRecordPresenter.setDialog(RestaurantUrl.Httptitle + RestaurantUrl.ADDMONEY + "cgid=" +
                        restaurantInfo.getId() + "&name=" + StringUtils.utf8Encode(investorInfo.getAccount_name()) + "&money=" + msg + "&phone=" +
                        investorInfo.getPhone() + "&super_phone=" + loginInfo.getStaff_phone() +
                        "&permillage=" + investRuleInfo.getAccount_permillage(), alertDialog);
            }
        }
    }

    @Override
    public void onRefresh() {
        addData();
    }

    @Override
    public void recRes(int res, AlertDialog alertDialog) {
        if (res == 1) {
            if (alertDialog != null) {
                if (alertDialog.isShowing())
                    alertDialog.dismiss();
            }
            toast("提交成功。");
        } else {
            toast("提交失败，请重试。");
        }
        onRefresh();
    }

    @Override
    public void recOpenCloseRes(int res, DialogInterface dialog) {
        if (res == 1) {
            if (dialog != null) {
                dialog.dismiss();
            }
            toast("提交成功。");
            setResult(1);
            finish();
        } else {
            toast("提交失败，请重试。");
        }

    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }
}
